<?php
require_once '../utils/Database.php';
require_once '../utils/WeChatAuth.php';
require_once '../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

$user = $auth->getCurrentUser();
if (!$user) {
    Response::authError('请先登录');
}

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'POST':
        // 提交意见反馈
        $data = [
            'user_id' => $user['id'],
            'feedback_type' => $input['feedback_type'] ?? '',
            'title' => $input['title'],
            'content' => $input['content'],
            'images' => isset($input['images']) ? json_encode($input['images']) : null,
            'contact_phone' => $input['contact_phone'] ?? '',
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $feedbackId = $db->insert('feedback', $data);
        
        if ($feedbackId) {
            Response::success(['feedback_id' => $feedbackId], '反馈提交成功');
        } else {
            Response::error('反馈提交失败');
        }
        break;
        
    case 'GET':
        if (isset($_GET['action'])) {
            switch ($_GET['action']) {
                case 'list':
                    // 获取用户反馈列表
                    $page = (int)($_GET['page'] ?? 1);
                    $limit = 10;
                    $offset = ($page - 1) * $limit;
                    
                    $feedbacks = $db->fetchAll(
                        "SELECT id, feedback_type, title, status, created_at 
                         FROM feedback 
                         WHERE user_id = ? 
                         ORDER BY created_at DESC 
                         LIMIT ? OFFSET ?",
                        [$user['id'], $limit, $offset]
                    );
                    
                    Response::success($feedbacks, '获取成功');
                    break;
                    
                case 'detail':
                    // 获取反馈详情
                    $id = (int)$_GET['id'];
                    
                    $feedback = $db->fetchOne(
                        "SELECT * FROM feedback WHERE id = ? AND user_id = ?",
                        [$id, $user['id']]
                    );
                    
                    if ($feedback) {
                        if ($feedback['images']) {
                            $feedback['images'] = json_decode($feedback['images'], true);
                        }
                        Response::success($feedback, '获取成功');
                    } else {
                        Response::notFound('反馈记录不存在');
                    }
                    break;
                    
                default:
                    Response::error('无效的操作');
            }
        } else {
            Response::error('缺少action参数');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>